package org.xiong.disk.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xiong.disk.bean.DownloadRecord;
import org.xiong.disk.bean.Msg;
import org.xiong.disk.bean.UploadRecord;
import org.xiong.disk.bean.User;
import org.xiong.disk.config.HdfsConfig;
import org.xiong.disk.service.DownloadRecordService;
import org.xiong.disk.service.UploadRecordService;
import org.xiong.disk.util.HdfsUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class ResponseController {


    @Autowired
    HdfsUtil hdfsUtil;
    @Autowired
    UploadRecordService uploadRecordService;
    @Autowired
    DownloadRecordService downloadRecordService;


    /**
     * 获取目录信息
     * @param session
     * @param path  需要获取目录的地址
     * @return
     * @throws Exception
     */
    @PostMapping("/data/getFilesInfo/{phone}")
    public Msg getFilesInfo(HttpSession session, @RequestParam(value = "path",defaultValue = "") String path) throws Exception {

        User loginUser = (User) session.getAttribute("loginUser");
        String newPath = loginUser.getPhone() ;
        if (!"".equals(path)) {
            newPath = path;
        }
        // 调用 hdfsUtil 的查询目录方法
        List<Map<String, Object>> maps = hdfsUtil.readPathInfo(newPath);
        log.info("path:{}",newPath);
        if (maps == null){
            return Msg.fail("失败").add("data", maps).add("curPath",path);
        }

        return Msg.success("成功").add("data", maps).add("curPath",path);
    }

    /**
     * 删除文件或者目录
     * @param path  需要删除的目录地址
     * @return
     * @throws Exception
     */
    @PostMapping("/data/deleteFile/{phone}")
    public Msg deleteFile(@RequestParam("path") String path) throws Exception {
        boolean isDelete = hdfsUtil.deleteFile(path);
        Msg msg;
        if (isDelete) {
            msg = Msg.success("删除成功");
        }else {
            msg = Msg.fail("删除失败");
        }

        return msg;
    }

    /**
     * 创建文件夹
     * @param path 创建目录位置
     * @return
     * @throws Exception
     */
    @PostMapping("/data/mkdirFolder/{user}")
    public Msg mkdirFolder(@RequestParam("path") String path) throws Exception {
        System.out.println(path);
        boolean isMkdir = hdfsUtil.mkdir(path);
        Msg msg;
        if (isMkdir){
            msg = Msg.success("创建成功");
        }else{
            msg = Msg.fail("创建失败");
        }
        return msg;
    }

    /**
     * 上传文件
     * @param files  封装后的文件对象
     * @param path  上传文件路径
     * @return 如果成功返回msg.success 否则返回 msg.fail
     */
    @PostMapping("/data/uploadFile/{user}")
    public Msg uploadFile(@RequestParam(value = "fileData",required = false) MultipartFile[] files,
                          @RequestParam("path") String path,@PathVariable("user") String user) throws Exception {
        Msg msg;
        UploadRecord uploadRecord;
        if (null != files){
            int uploadSign = 0;

            for (MultipartFile file : files) {
                boolean isUpload = hdfsUtil.uploadFile(file, path, file.getOriginalFilename());
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                if (isUpload){
                    uploadSign++;
                    // 记录文件的上传情况
                    uploadRecord = new UploadRecord(file.getOriginalFilename(), simpleDateFormat.format(date),"上传成功",path,user);

                }else {
                    uploadRecord = new UploadRecord(file.getOriginalFilename(), simpleDateFormat.format(date),"上传失败",path,user);
                }
                uploadRecordService.insertByUploadRecord(uploadRecord);
            }
            if (uploadSign == files.length){
                msg = Msg.success("上传成功");
            }else{
                msg = Msg.fail("有"+uploadSign+"文件上传失败");
            }
        }
        else{
            msg = Msg.fail("文件未上传");
        }
        return msg;
    }

    /**
     * 下载文件
     * @param path  下载文件路径
     * @return
     * @throws IOException
     */
    @GetMapping("/data/downloadFile/{user}")
    public OutputStream downloadFile(@RequestParam("path") String path,
                                     HttpServletResponse response,@PathVariable("user") String user) throws IOException {
        if ("".equals(path)){
            return null;
        }
        String[] split = path.split("/");
        // 设置请求头 标志为可下载数据
        String fileName = new String(split[split.length-1].getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1 );
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        response.setStatus(HttpServletResponse.SC_OK);

        OutputStream outputStream = hdfsUtil.downloadFile(path, response.getOutputStream());

        DownloadRecord downloadRecord;
        // 创建当前时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (outputStream != null){

            // 保存下载记录
            downloadRecord = new DownloadRecord(split[split.length-1],simpleDateFormat.format(date),"下载成功",path,user);
        }else{
            downloadRecord = new DownloadRecord(split[split.length-1],simpleDateFormat.format(date),"下载失败",path,user);
        }
        downloadRecordService.insertByDownloadRecord(downloadRecord);

        return outputStream;
    }

    /**
     * 获取上传记录
     * @param page
     * @param session
     * @return
     */
    @PostMapping("/uploadRecord/")
    public Msg uploadRecord(@RequestParam(value = "page",defaultValue = "1") String page, HttpSession session){
        Msg msg;
        User loginUser =(User)session.getAttribute("loginUser");
        List<UploadRecord> uploadRecord = uploadRecordService.getUploadRecord(loginUser.getPhone());
        if (uploadRecord == null){
            msg = Msg.fail("查询失败！");
        }else{
            msg = Msg.success("查询成功").add("data",uploadRecord);
        }

        return msg;
    }

    @PostMapping("/downloadRecord/")
    public Msg downloadRecord(@RequestParam(value = "page",defaultValue = "1") String page,HttpSession session){

        Msg msg;
        User loginUser =(User)session.getAttribute("loginUser");
        List<DownloadRecord> downloadRecords = downloadRecordService.getDownRecord(loginUser.getPhone());
        if (downloadRecords == null){
            msg = Msg.fail("查询失败！");
        }else{
            msg = Msg.success("查询成功").add("data",downloadRecords);
        }

        return msg;

    }

}
